package cc.bluemc.modules.adminUser.action;

import cc.bluemc.modules.adminUser.entity.AdminUser;
import cc.bluemc.modules.adminUser.entity.Role;
import cc.bluemc.modules.adminUser.service.AdminUserService;
import cc.bluemc.modules.adminUser.service.RoleService;
import cc.bluemc.platform.comm.BaseAction;
import cc.bluemc.platform.jdbctemplatetool.exception.NoColumnAnnotationFoundException;
import cc.bluemc.platform.jdbctemplatetool.exception.NoIdAnnotationFoundException;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/user")
public class AdminUserAction extends BaseAction{
	private Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private AdminUserService userService;
	@Autowired
	private RoleService roleService;

	
	/**
	 * 注册页面
	 * @return
	 * @throws NoColumnAnnotationFoundException 
	 * @throws NoIdAnnotationFoundException 
	 */
	@RequestMapping("regist")
	public String registForm(Integer userId) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		return "adminUser/userRegister";
	}
	
	/**
	 * 修改密码
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("updatePwd")
	public String updatePwd(AdminUser user,Model model){
		model.addAttribute("bean", user);
		return "adminUser/userUpdatePwdForm";
	}
	/**
	 * 登录
	 * @param user
	 * @param model
	 * @throws NoColumnAnnotationFoundException 
	 * @throws NoIdAnnotationFoundException 
	 */
	@RequestMapping("login")
	public String login(AdminUser user,Model model,RedirectAttributes attributes) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		 String msg ="";
		/*/
		 //未使用shiro
		if(null==user_T||!user_T.getPassword().equals(Md5Util.encryptPassword(user.getUserName(), user.getPassword(),user_T.getSalt()))){
			msg = "账号错误!";
			logger.info(msg);
			return null;
		}
		/*/
		 //使用shiro
		Subject subject = SecurityUtils.getSubject();
	    UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());
	   
	    try {  
	        //4、登录，即身份验证  
	        subject.login(token);  
	    } 	catch (UnknownSessionException use) {
			msg = "异常会话!";
			logger.info(msg);
		}
		catch (UnknownAccountException ex) {
			msg = "账号错误!";
			logger.info(msg);
		}
		catch (IncorrectCredentialsException ice) {
			msg = "密码错误!";
			logger.info(msg);
		}
		catch (AuthenticationException ae) {
			msg = "用户名或密码错误!";
			logger.info(msg);
		}
		catch (Exception e) {
			msg = "出现未知异常,请与系统管理员联系!";
			logger.info(msg);
		} finally{
			if(token != null){
				token.clear();
			}
		}
		if(!subject.isAuthenticated()){
			attributes.addAttribute("msg", msg);
			 return "redirect:/web/login.jsp";
		}
		//*/
	    return "redirect:/index.jsp";
	}
	/**
	 * 登出
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(){
		Subject subject = SecurityUtils.getSubject();  
		subject.logout();
		return "redirect:/web/login.jsp";
	}
	/**
	 * 用户表单页面
	 * @param id
	 * @param model
	 * @return
	 * @throws NoIdAnnotationFoundException
	 * @throws NoColumnAnnotationFoundException
	 */
	@RequestMapping("form")
	public String addForm(Integer id,Model model) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		if(null!=id){
			AdminUser user= userService.getAdminUser(id);
			if(null!=user){
				model.addAttribute("bean", user);
				model.addAttribute("ownRole", roleService.getUserRoles2(user));
			}
		}
		//角色
		List<Role> roles= roleService.getUserableRoles();
		model.addAttribute("roles",roles);
		return "adminUser/userForm";
	}
	/**
	 * 保存用户
	 * @param user
	 * @param model
	 * @param roleIds
	 * @return
	 */
	@RequestMapping("save")
	public String save(AdminUser user,Model model,Integer [] roleIds){
		try {
			if(null==user.getId()){
				userService.save(user, roleIds);
			}else{
				userService.updateBean(user,roleIds);
			}
			resultMap.setSuccess(true);
			
		} catch (Exception e) {
			resultMap.setSuccess(false);
			resultMap.setMsg("保存失败");
		}
		return "redirect:list";
	}
	/**
	 * 用户列表
	 * @param model
	 * @return
	 */
	@RequestMapping("list")
	public String list(Model model){
		resultMap.setSuccess(true);
		page = userService.getList(page);
		resultMap.setData(page);
		model.addAttribute(_RESULTMAP,resultMap);
		return "adminUser/userList";
	}
}
